/*
The MIT License (MIT)

Copyright (c) 2013 Mike Dapiran, Brian May, Richard Pospesel, and Bert Wierenga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software 
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "Scene.h"
#include "..\Interfaces\IDirector.h"
#include "..\Interfaces\IGame.h"
#include "..\Managers\DirectorIndex.h"
#include "..\Managers\ContentLibrary.h"
#include "..\Managers\Messenger.h"

#include "..\Messages\ScenePausedMessage.h"
#include "..\Messages\SceneResumedMessage.h"

#include "../Content/Prefab.h"

#include "tinyxml.h"
#ifdef _OPENMP
#include <omp.h>
#endif

namespace Hogshead
{
	namespace Core
	{
		ContentCPP(Hogshead::Core::Scene, Scene)

			Scene::Scene() : _game_object_table(3, 1), _scene_processes_completed(SceneProcessesCompleted::NONE)
		{
			_scene_phase = ScenePhase::None;
			_parent_game = NULL;
			_root_game_object = NULL;
			_root_gui_panel = NULL;
			_ref_count = 0;
			_table_dirty = true;
			_table_dirty_layer = 0;
		}

		Scene::~Scene()
		{

		}

		void Scene::setDirtyLayer(int in_layer)
		{
			if(in_layer < 0)
				error("Invalid Dirty Layer");
			_table_dirty = true;
			if(in_layer < _table_dirty_layer)
				_table_dirty_layer  = in_layer;
		}

		void Scene::buildGameObjectTable()
		{
			_game_object_buffer.clear();
			// add list of gameobjects above the dirty layer to buffer
			for(int k = 0; k < _game_object_table.width(_table_dirty_layer); k++)
				_game_object_buffer.add(_game_object_table[_table_dirty_layer][k]);

			_game_object_table.clearBelow(_table_dirty_layer);
			
			while(_game_object_buffer.size() > 0)
			{
				// pop game object off stack
				GameObject* current = _game_object_buffer.removeLast();
				// set the game objects layer based on parent
				if(current->_parent_game_object != NULL)
					current->_layer = current->_parent_game_object->_layer+1;
				// add to the table
				while(_game_object_table.rows() <= current->_layer)
					_game_object_table.addRow();
				_game_object_table.add(current->_layer, current);
				// get number of children
				int children = current->_child_game_objects.size();

				// get our child game object buffer
				GameObject* const*  child_buffer = current->_child_game_objects;
				///  push them all on the stack
				for(int k = 0; k < children; k++)
					_game_object_buffer.add(child_buffer[k]);
			}

			_table_dirty = false;
			_table_dirty_layer = Integer::MaxInt;

		}

		struct updateParams
		{
			const GameTimer* gt;
			GameObject** row;
			int width;
		};

		// called by game on each frame
		void Scene::update(const GameTimer& in_gt)
		{
			_scene_phase = ScenePhase::GameObjectUpdate;
			// recursive update
			//_root_game_object->update(in_gt);
			
			//update the root gui panel
			if(_root_gui_panel)
				_root_gui_panel->update(in_gt);

			
			// iterative update
			if(_table_dirty) buildGameObjectTable();
			


			/// PARALLEL
			if(_parent_game->getMultithreadUpdate())
			{
				#ifdef _OPENMP
				omp_set_num_threads(1);

				for(int k = 0; k < _game_object_table.rows(); k++)
				{
					int row_width = _game_object_table.width(k);
					if(row_width == 0)
						break;

					GameObject** row = _game_object_table[k];
					#pragma omp parallel for
					for(int j = 0; j < row_width; j++)
						row[j]->shallowUpdate(in_gt);
				}
				#else

				for(int k = 0; k < _game_object_table.rows(); k++)
				{
					int row_width = _game_object_table.width(k);
					if(row_width == 0)
						break;

					updateParams up;
					up.gt = &in_gt;
					up.row = _game_object_table[k];
					up.width = row_width;
					Parallel::forLoop(0, row_width-1,Scene::update_game_object, &up);
				}

				#endif
			}
			// SERIAL
			else
			{
				for(int k = 0; k < _game_object_table.rows(); k++)
				{
					int row_width = _game_object_table.width(k);
					if(row_width == 0)
						break;

					GameObject** row = _game_object_table[k];
					for(int j = 0; j < row_width; j++)
						row[j]->shallowUpdate(in_gt);
				}
			}
			

			// sync point
			_scene_phase = ScenePhase::DirectorUpdate;
			// update directors
			for(int k = 0; k < _directors.size(); k++)
				_directors[k]->update(in_gt);
		}

		// callback function fo rupdating a single game obect shallowly
		void Scene::update_game_object(int j, void* data)
		{
			updateParams* params = (updateParams*)data;
			if(params->width  <= j)
				Hogshead::Common::error();
			params->row[j]->shallowUpdate(*params->gt);
		}

		void Scene::draw()
		{
			for(int k = 0; k < _directors.size(); k++)
				_directors[k]->draw();
		}

		// add a director to this scene
		void Scene::addDirector(IDirector* in_director, bool is_drawable)
		{
			_director_map.add(in_director->directorName(), in_director);
			_directors.add(in_director);
			in_director->setScene(this);
		}

		// get a director pointer by type
		IDirector* Scene::getDirector(const String& in_name)
		{
			IDirector* result = NULL;
			_director_map.tryGetValue(in_name, result);
			/*if(result == NULL)
			{
				StringBuilder sb;
				sb << "Could not find director of type \'" << in_name << "\' in scene";
				throw Exception(sb);
			}*/
			return result;
		}

		// add a named game object to this scene
		void Scene::addGameObject(GameObject* in_game_object)
		{
			//see if there is any game objects with this name already.
			if( _game_object_map.contains( in_game_object->name() ) )
			{
				Vector<GameObject*>& list_with_ins_name = _game_object_map[in_game_object->name()];
				list_with_ins_name.add( in_game_object );
			}
			else
			{
				_game_object_map.add( in_game_object->name(), Vector<GameObject*>() );
				Vector<GameObject*>& list_with_ins_name = _game_object_map[in_game_object->name()];
				list_with_ins_name.add( in_game_object );
			}
		}

		// get back a game object by it's name
		GameObject* Scene::getGameObject(const String& in_name)
		{
			if( _game_object_map.contains( in_name ) )
			{
				Vector<GameObject*>& list = _game_object_map[ in_name ];

				//just return the first one
				return list[0];
			}
			else
			{
				return NULL;
			}
			
		}

		Vector<GameObject*>* Scene::getGameObjects(const String& in_name)
		{
			if( _game_object_map.contains( in_name ) )
			{
				Vector<GameObject*>& list = _game_object_map[ in_name ];
				Vector<GameObject*>* result = &list;
				//just return the first one
				return result;
			}
			else
			{
				return NULL;
			}			
		}

		// remove a game object from the scene by it's name
		void Scene::RemoveReleaseGameObject(GameObject* in_to_remove)
		{
			if( _game_object_map.contains( in_to_remove->name() ) )
			{
				Vector<GameObject*>& list = _game_object_map[ in_to_remove->name() ];
				list.remove( in_to_remove );
			}
			else
			{
				error("Attempting to remove a GameObject from the Scene but There are no GameObjects in the Scene with it's name");
			}
		}

		void Scene::setRootGameObject(GameObject* in_game_object)
		{
			in_game_object->_owner = this;
			_root_game_object = in_game_object;
		}

		GameObject* Scene::getRootGameObject()
		{
			return _root_game_object;
		}

		void Scene::addGUIPanel(GUIPanel* in_gui_panel)
		{
			_gui_panel_map.add(in_gui_panel->name(), in_gui_panel);
		}

		GUIPanel* Scene::getGUIPanel(const String& in_name)
		{
			GUIPanel* panel_result = NULL;
			_gui_panel_map.tryGetValue(in_name, panel_result);
			return panel_result;
		}

		void Scene::setRootGUIPanel(GUIPanel* in_panel)
		{
			in_panel->_parent_scene = this;
			_root_gui_panel = in_panel;
		}

		GUIPanel* Scene::getRootGUIPanel()
		{
			return _root_gui_panel;
		}

		Scene* Scene::loadScene(const String& in_filename)
		{
			FileInputStream fis(in_filename);
			StringBuilder sb;
			for(int k = fis.read(); k >= 0; k = fis.read())
				sb << (char)k;
			fis.close();


			Scene* result = new Scene();
			result->readXML(sb);
			
			return result;
		}

		
		void Scene::initialize()
		{
			this->_scene_phase = ScenePhase::MessageHandling;
			//hout << *_root_game_object;
			_root_game_object->initialize();

			if(_root_gui_panel)
				_root_gui_panel->initialize();

			for(int k = 0; k < _directors.size(); k++)
				_directors[k]->initialize();
		}

		

		void Scene::explicitLoad()
		{
			error("You cannot load a Scene in this manner, XML is required");
		}

		void Scene::readXML(const String& in_xml)
		{
			this->_scene_phase = ScenePhase::Loading;

			TiXmlDocument document;
			document.Parse(in_xml);

			TiXmlElement* node = document.RootElement();

			TiXmlElement* game_object_xml_element = NULL;
			TiXmlElement* gui_panel_xml_element = NULL;

			this->_key = String(node->Attribute("key"));
			this->_path = String(node->Attribute("path"));

			//used to get the absolute path to it 
			this->_path = ContentLibrary::getCompleteContentString( this->_path );

			if(node)
			{
				TiXmlNode* child = 0;

				while(child = node->IterateChildren(child))
				{
					TiXmlElement* child_element = child->ToElement();
					if(!child_element)	// a comment mostlikely
						continue;

					const char* tag = child_element->Value();

					if(String::equals("GameObject", tag))
					{
						// parse a game object
						if(this->_root_game_object == NULL)
						{
								
							game_object_xml_element = child_element;

							GameObject* go = Factory::acquire<GameObject>();
							this->setRootGameObject(go);
							String root_xml(*game_object_xml_element);
							this->_root_game_object->readXML(root_xml, this);
							_root_game_object->setOwner( this );
							_root_game_object->_layer = 0;
							_game_object_table.addRow();
							_game_object_table.add(0, _root_game_object);
						}
						else
						{
							error("Scene already has a root GameObject");
						}

					}
					else if(String::equals("Director", tag))
					{
						
						const char* director_type = child_element->Attribute("type");
						if(director_type != NULL)
						{
							IDirector* prototype = DirectorIndex::getPrototype(director_type);
							if(prototype == NULL)
							{
								StringBuilder sb;
								sb << "Could not find prototype Director of type \"" << director_type << "\"" << endl;
								sb << director_type << " needs to be added to your scene and registered in Game::registerDirectorClasses()";
								Exception& e = Exception(sb);
								error(e);
							}
							IDirector* new_director = prototype->instance();

							this->addDirector(new_director);
							String director_xml(*child_element);
							new_director->readXML(director_xml);
						}
					}
					else if(String::equals("Prefab", tag))
					{
						ContentLibrary::loadAndParseContentXML(child_element->Attribute("path"));
					}
					else if(String::equals("AssetList", tag))
					{
						ContentLibrary::loadAndParseAssetList( child_element->Attribute("path"));
					}
					else if(String::equals("GUIPanel", tag))
					{
						if(this->_root_gui_panel == NULL)
						{
							gui_panel_xml_element = child_element;

							GUIPanel* gp = Factory::acquire<GUIPanel>();
							this->setRootGUIPanel(gp);
							String root_xml(*gui_panel_xml_element);
							this->_root_gui_panel->readXML(root_xml, this);
							_root_gui_panel->setScene( this );
						}
						else
						{
							error("Scene already has a root GameObject");
						}
					}
					else
					{
						error("Error parsing XML node");
					}
					
				}
				// we have to parse gameobject last because may depend on scene's directors
				if(game_object_xml_element == NULL)
				{
					error("Problem parsing XML node; no root GameObject found");
				}
			}
			//hout << *_root_game_object << endl;
		}

		IGame* Scene::getGame()
		{
			return _parent_game;
		}

		void Scene::registerForMessages(IDirector* in_director)
		{
			_messaged_directors.add(in_director);
		}

		void Scene::registerForMessages(IComponent* in_component)
		{
			_messaged_components.add(in_component);
		}

		void Scene::pause()
		{
			this->sendMessage(Factory::acquire<ScenePausedMessage>());
		}

		void Scene::resume()
		{
			this->sendMessage(Factory::acquire<SceneResumedMessage>());
		}

		void Scene::finalize()
		{
			if(this->_root_game_object)
				Factory::release( this->_root_game_object );

			if(this->_root_gui_panel)
				Factory::release(this->_root_gui_panel);

			for( int i = 0; i < this->_directors.size(); i++ )
			{
				Factory::release( _directors[i] );
			}

			IGameObjectTreeHolder::finalize();

			_scene_phase = ScenePhase::None;
		}
	}
}